// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const timeutil = require('./timeutil');
const db = cloud.database();
const PART = 'cloud-participant';
const GROUP = 'cloud-activities-groups';
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  /**获取操作类型 */
  let action = event.action;
  switch(action){
    case 'saveOne':{
      return await saveOne(event,context);
      break
    }
    case 'getOne':{
      return await getOne(event,context);
      break
    }
    case 'getList':{
      /**获取参与列表 */
      let step = event.step || 0
      let groupId = event.groupId;
      return await db.collection(PART).where({
        groupId,
        status:1
      }).skip(step).get();
      break
    }
  }
}
async function getOne(event,context){
  let docId = event.docId;
  let queryRes = await db.collection(PART).doc(docId).get();
  return queryRes.data;
  /**条件跳转 */
}
async function saveOne(event,context){
  const wxContext = cloud.getWXContext()
  let openid = wxContext.OPENID;
  /**进行表单校验 */
  
  /**提取部分参数 */
  let realName = event.realName;
  let mobile = event.mobile;
  /**获取userId */
  let userRes = await cloud.callFunction({
    name:'cloud-user-extend',
    data:{
      openid,
      realName,
      mobile
    }
  })
  if(userRes.result.errCode == -1){
    return userRes.result;
  }
  let userId = userRes.result.docId;
  /**根据groupId 获取更多信息 */
  let groupId = event.groupId;
  let activityId = null;
  let groupName = null;
  try {
    let groupRes = await db.collection(GROUP).doc(groupId).get();
    let groupData = groupRes.data;
    activityId = groupData.activityId;
    groupName = groupData.groupName;
  } catch (error) {
    return {
      errCode:-1,
      errMsg:'请传入正确的组别ID'
    }
  }
  /**计算simId */
  let simIdRes = await db.collection(PART).where({
    activityId
  }).count();
  simId = simIdRes.total + 1
  /**正常情况下 -- 继续写入 */
  return await db.collection(PART).add({
    data:{
      simId,
      activityId,
      groupId,
      realName,
      mobile,
      groupName,
      userId,
      openid,
      userIntro:event.userIntro,
      userImage:event.imageList,
      userVideo:event.videoList,
      voteNum:0,
      status:0,
      _createTime:timeutil.TimeCode(),
      _updateTime:timeutil.TimeCode()
    }
  })
}